package vaani.swar.grammar;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.speech.recognition.GrammarException;
import javax.speech.recognition.RuleGrammar;

/**
 *
 * @author sourcemorph
 */
public class ApplicationGrammarConstructor extends GenericGrammarConstructor {

    public static void constructGrammar() {
        try {
            if(jsgfGrammarManager == null) {
                System.out.println("is null");
            }
            try {
                jsgfGrammarManager.loadJSGF("application");
            } catch(NullPointerException ex) {
                ex.printStackTrace();
            }
            RuleGrammar ruleGrammar = jsgfGrammarManager.getRuleGrammar();
            addRule(ruleGrammar, "start", "I (want|wish) [you] to | let me");
            addRule(ruleGrammar, "aux", "open | find");
            addRule(ruleGrammar, "middle", "[an|the] (application | program) [to | for]");
            addRule(ruleGrammar, "activity", "<verb> <noun>");
            addRule(ruleGrammar, "verb", getApplicationRule("verb"));
            addRule(ruleGrammar, "noun", getApplicationRule("noun"));
            addRule(ruleGrammar, "complete", "[<start>] <aux> <middle> <activity>");

        } catch(IOException ex) {
            ex.printStackTrace();
        } catch(GrammarException ex) {
            ex.printStackTrace();
        }
    }

    @SuppressWarnings("empty-statement")
    public static String getApplicationRule(String tag) {
        String tempRule = null;
        InputStream fstream = Thread.currentThread().getContextClassLoader().getResourceAsStream("data/commonapplicationrequests.txt");
        if(fstream == null) {
            System.out.println("failed to find grammar construction data resource \"commmonapplicationrequests.txt\"");
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(fstream));
        try {
            while(! reader.readLine().equalsIgnoreCase("<" + tag + ">"));
            tempRule = reader.readLine();
            String line;
            while(! (line = reader.readLine()).equalsIgnoreCase("<\\"+tag+">")) {
                tempRule += " | " + line;
            }
        } catch(IOException ex) {
            ex.printStackTrace();
        }
        return tempRule;
    }

    /*main for testing
    public static void main(String [] args) {
        constructGrammar();
    }*/

}
